6805

34 分钟

#C 语言标准库头文件 threads.h

这个头文件提供 线程 相关的功能。例如线程控制、互斥量、条件变量、线程局部存储等。

#常量

标准说明
TSS_DTOR_ITERATIONSC11线程局部存储指针析构函数被 thrd_exit 调用的最大次数
线程状态枚举标准说明
thrd_successC11表示成功
thrd_nomemC11表示内存不足
thrd_timedoutC11表示超时
thrd_busyC11表示资源不可用
thrd_errorC11表示错误
互斥量类型枚举标准说明
mtx_plainC11普通互斥量
mtx_recursiveC11递归互斥量
mtx_timedC11定时互斥量

#类型

类型标准说明
thrd_tC11线程 ID
mtx_tC11互斥量 ID
cnd_tC11条件变量 ID
tss_tC11线程局部存储指针 ID
thrd_start_tC11线程启动函数的类型(int(*)(void*)
tss_dtor_tC11线程局部存储指针析构函数的类型(void(*)(void*)

#函数

线程标准说明
thrd_createC11创建线程
thrd_equalC11判断两个线程 ID 是否表示同一个线程
thrd_currentC11获取当前线程的 ID
thrd_sleepC11阻塞当前线程一段时间
thrd_yieldC11使当前线程让出
thrd_exitC11退出指定线程
thrd_detachC11分离指定线程
thrd_joinC11阻塞当前线程,直到指定线程退出

#推荐阅读

#示例

#include <stdio.h> #include <threads.h> #include <stdlib.h> // 示例1: 简单的线程函数 int simple_thread(void *arg) { int *id = (int*)arg; printf("线程 %d 正在运行\n", *id); return 0; } // 示例2: 带互斥锁的线程函数 mtx_t mutex; int shared_counter = 0; int counter_thread(void *arg) { int *iterations = (int*)arg; for (int i = 0; i < *iterations; ++i) { mtx_lock(&mutex); shared_counter++; mtx_unlock(&mutex); } return 0; } // 示例3: 使用条件变量 cnd_t condition; mtx_t condition_mutex; int data_ready = 0; int producer_thread(void *arg) { int *value = (int*)arg; mtx_lock(&condition_mutex); printf("生产者: 生成数据 %d\n", *value); data_ready = 1; cnd_signal(&condition); mtx_unlock(&condition_mutex); return 0; } int consumer_thread(void *arg) { (void)arg; // 未使用参数 mtx_lock(&condition_mutex); while (!data_ready) { printf("消费者: 等待数据...\n"); cnd_wait(&condition, &condition_mutex); } printf("消费者: 接收到数据\n"); mtx_unlock(&condition_mutex); return 0; } // 示例函数: 演示线程创建和使用 int main(void) { thrd_t threads[3]; int ids[3] = {1, 2, 3}; printf("=== 简单线程示例 ===\n"); for (int i = 0; i < 3; i++) { thrd_create(&threads[i], simple_thread, &ids[i]); } for (int i = 0; i < 3; i++) { thrd_join(threads[i], NULL); } printf("\n=== 互斥锁示例 ===\n"); mtx_init(&mutex, mtx_plain); int iterations = 100000; thrd_t t1, t2; thrd_create(&t1, counter_thread, &iterations); thrd_create(&t2, counter_thread, &iterations); thrd_join(t1, NULL); thrd_join(t2, NULL); printf("最终计数器值: %d (应为: %d)\n", shared_counter, 2 * iterations); mtx_destroy(&mutex); printf("\n=== 条件变量示例 ===\n"); mtx_init(&condition_mutex, mtx_plain); cnd_init(&condition); int value = 42; thrd_t producer, consumer; thrd_create(&consumer, consumer_thread, NULL); thrd_sleep(&(struct timespec){.tv_sec=1}, NULL); // 让消费者先启动 thrd_create(&producer, producer_thread, &value); thrd_join(producer, NULL); thrd_join(consumer, NULL); mtx_destroy(&condition_mutex); cnd_destroy(&condition); return 0; }

运行结果:

=== 简单线程示例 === 线程 1 正在运行 线程 2 正在运行 线程 3 正在运行 === 互斥锁示例 === 最终计数器值: 200000 (应为: 200000) === 条件变量示例 === 消费者: 等待数据... 生产者: 生成数据 42 消费者: 接收到数据

创建于 2025/8/21

更新于 2025/8/22